clc;
clear all;
close all;
% ssa-cnn-lstm-attention
[num,txt,raw]=xlsread('match.xlsx');
[num1,txt1,raw1]=xlsread('discriminant.xlsx');
raw2=raw1(3:end,:);
a1=raw2(:,3);
a2=raw2(:,2);
a3=raw2(:,8:15);
a4=raw2(:,17:107);
a5=raw2(:,115:128);
a6=[a3,a4,a5];
raw3=raw(2:end,:);
raw4=raw3(:,1);
raw5=raw3(:,3);
raw6=raw3(:,7);
raw7=raw3(:,8);
L=raw3(:,6);
[mm,nn]=size(L);
L1=[];
for i=1:mm
    aa=2;
    L1=[L1;{aa}];
end
name1=[raw4;raw7];
time1=[raw5;raw6];
label1=[L;L1];
[mm1,nn1]=size(name1);
[mm2,nn2]=size(a2);
a11=cell2mat(a1);
time2=cell2mat(time1);
qc=[];
qc1=[];
for i=1:mm1
    name2=cell2mat(name1(i));
    name2=string(name2);
    time3=time2(i);
    for j=1:mm2
        name3=cell2mat(a2(j));
        name3=string(name3);
        if (strcmp(name2,name3)==1)&&time3==a11(j)
            qc=[qc;j];
           qc1=[qc1;i];
         break;
        end
    end
end
newname=name1(qc1);
newtime=time2(qc1);
newlabel=label1(qc1);
a7=a6(qc,:);
[mm3,nn3]=size(newtime);
newtime1=[];
for i=1:mm3
    newtime1=[newtime1;{newtime(i)}];
end
data1=[newname,newtime1,a7,newlabel];
[mm4,nn4]=size(data1);
ty=[];
for j=3:nn4
        [mm5,nn6]=find(isnan(cell2mat(data1(:,j))));
        if isempty(nn6)==0
            ty=[ty,j];
        end
end
data1(:,ty)=[];
data=cell2mat(data1(:,3:end-1));
label=cell2mat(data1(:,end));
[mm6,nn6]=size(data);
df=[];
for i=1:nn6
[k1,k2]=find(data(:,i)==0);
if mm6==sum(k2)
    df=[df,i];
end
end

df1=[];
for i=1:nn6
[k1,k2]=find(data(:,i)==1);
if mm6==sum(k2)
    df1=[df1,i];
end
end
df2=[df,df1];
data(:,df)=[];
data=zscore(data);     
r=corrcoef(data);      
[vec1,lamda,rate]=pcacov(r);               
f=repmat(sign(sum(vec1)),size(vec1,1),1);    
vec2=vec1.*f;           
num = max(find(lamda>1)); 
df=data*vec2(:,1:num);   
tf=df*rate(1:num)/100;    
[stf,ind]=sort(tf,'descend'); 
stf=stf'; 
ind=ind';       
newdata=data(ind,:);
newdata11=newdata;
ccoefficients = corr(newdata11, cell2mat(newlabel), 'Type', 'Pearson');
threshold = 0.01;
hfeatures = find(abs(ccoefficients) > threshold);
disp(hfeatures );
newdata=newdata11(:,hfeatures);
res =newdata;
num_class = length(unique(cell2mat(newlabel))); 
label=cell2mat(newlabel);
num_dim = size(res, 2) ;             
num_res = size(res, 1);                  
num_size = 0.7;   
sa=randperm(num_res);
res = res(sa, :);   
label1=label(sa, :); 
flag_conusion = 1;                       
P_train = res(1:fix(num_res*0.7),:)'; 
P_test = res(fix(num_res*0.7)+1:end,:)'; 
T_train = label1(1:fix(num_res*0.7),:)'; 
T_test = label1(fix(num_res*0.7)+1:end,:)'; 
M = size(P_train, 2);
N = size(P_test , 2);
[P_train, ps_input] = mapminmax(P_train, 0, 1);
P_test  = mapminmax('apply', P_test, ps_input);
t_train =  categorical(T_train)'; 
t_test  =  categorical(T_test )';
P_train =  double(reshape(P_train, num_dim, 1, 1, M));
P_test  =  double(reshape(P_test , num_dim, 1, 1, N));
for i = 1 : M
    p_train{i, 1} = P_train(:, :, 1, i);
end
for i = 1 : N
    p_test{i, 1}  = P_test( :, :, 1, i);
end
SearchAgents_no = 8;
Max_iteration = 5;
dim = 3;          
lb = [1e-3,10 1e-4];
ub = [1e-2, 30,1e-1];
fitness = @(x)fical(x);
[Best_score,Best_pos,curve]=SSA(SearchAgents_no,Max_iteration,lb ,ub,dim,fitness);
Best_pos(1, 2) = round(Best_pos(1, 2));   
best_hd  =100; 
best_lr= 0.001;
best_l2 = 0.01;
lgraph = layerGraph();
tempLayers = [
    sequenceInputLayer([num_dim, 1, 1], "Name", "input_sequence")
    sequenceFoldingLayer("Name", "seqfold_layer")];
lgraph = addLayers(lgraph, tempLayers);
tempLayers = convolution2dLayer([3, 1], 32, "Name", "conv_1");
lgraph = addLayers(lgraph, tempLayers);
tempLayers = [
    reluLayer("Name", "relu_1")
    convolution2dLayer([3, 1], 64, "Name", "conv_2")
    reluLayer("Name", "relu_2")];
lgraph = addLayers(lgraph, tempLayers);
tempLayers = [
    globalAveragePooling2dLayer("Name", "gapool")
    fullyConnectedLayer(16, "Name", "fc_2")
    reluLayer("Name", "relu_3")
    fullyConnectedLayer(64, "Name", "fc_3")
    sigmoidLayer("Name", "sigmoid")];
lgraph = addLayers(lgraph, tempLayers);

tempLayers = multiplicationLayer(2, "Name", "multiplication");
lgraph = addLayers(lgraph, tempLayers);
tempLayers = [
    sequenceUnfoldingLayer("Name", "sequnfold_layer")
    flattenLayer("Name", "flatten")
    lstmLayer(best_hd, "Name", "lstm", "OutputMode", "last")
    fullyConnectedLayer(num_class, "Name", "fc_final")
    softmaxLayer("Name", "softmax")
    classificationLayer("Name", "classification")];
lgraph = addLayers(lgraph, tempLayers);
lgraph = connectLayers(lgraph, "seqfold_layer/out", "conv_1");
lgraph = connectLayers(lgraph, "seqfold_layer/miniBatchSize", "sequnfold_layer/miniBatchSize");
lgraph = connectLayers(lgraph, "conv_1", "relu_1");
lgraph = connectLayers(lgraph, "conv_1", "gapool");
lgraph = connectLayers(lgraph, "relu_2", "multiplication/in2");
lgraph = connectLayers(lgraph, "sigmoid", "multiplication/in1");
lgraph = connectLayers(lgraph, "multiplication", "sequnfold_layer/in");
options = trainingOptions('adam', ...
    'MaxEpochs', 500, ...
    'InitialLearnRate', best_lr, ...
    'L2Regularization', best_l2, ...
    'LearnRateSchedule', 'piecewise', ...
    'LearnRateDropFactor', 0.1, ...
    'LearnRateDropPeriod', 400, ...
    'Shuffle', 'every-epoch', ...
    'ValidationPatience', Inf, ...
    'Plots', 'training-progress', ...
    'Verbose', false);

net = trainNetwork(p_train, t_train, lgraph, options);
t_sim1 = predict(net, p_train); 
t_sim2 = predict(net, p_test ); 
T_sim1 = vec2ind(t_sim1');
T_sim2 = vec2ind(t_sim2');
error1 = sum((T_sim1 == T_train))/M * 100 ;
error2 = sum((T_sim2 == T_test)) /N * 100 ;

figure
plot(1: M,T_sim1,'o','Color',[255 0 255]./255,'linewidth',1)    
hold on
plot(1: M,T_train,'*','Color',[0 0 0]./255,'linewidth',1)  
grid

figure
plot(1: N,T_sim2,'o','Color',[250 180 60]./255,'linewidth',2)    
hold on
plot(1: N,T_test,'*','Color',[0 0 0]./255,'linewidth',2)
grid
    figure
    cm = confusionchart(T_train, T_sim1);
    cm.Title = 'Confusion Matrix for Train Data';
    cm.ColumnSummary = 'column-normalized';
    cm.RowSummary = 'row-normalized';
    figure
    cm = confusionchart(T_test, T_sim2);
    cm.Title = 'Confusion Matrix for Test Data';
    cm.ColumnSummary = 'column-normalized';
    cm.RowSummary = 'row-normalized';

